(function() {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:itemList
     * @description
     * # itemList 
     */
    angular.module('webApp')
        //调用页面的方法
        .run(["$templateCache", "dataService",
            function($templateCache, dataService) {
                var tplName = "views/directives.printer.html";
                dataService.tpl(tplName).then(function(html) {
                    $templateCache.put(tplName, html);
                });
            }
        ])
        .directive('printer', function($templateCache, $compile, $timeout, helper) {
            return {
                restrict: 'E',
                // template: "<a href='javascript:void(0);' class='sui-btn btn-default'  ng-click='addItem();'>+{{isChoseItem?'chose_item':'chose_item_sku' | translate}}</a> ",
                template: $templateCache.get("views/directives.printer.html"),
                // template:,
                scope: {
                    shopid: "@",
                    printPub: "@",
                    type: "@"
                },
                controller: ['$rootScope', '$scope', 'dataService', '$timeout', '$state',
                    function($rootScope, $scope, dataService, $timeout, $state) {

                        // console.error("$scope.type_id", $scope.type, $scope.shopid);
                        $scope.init = function() {
                            // console.log("$scope.type_id", $scope.type, $scope.shopid);
                            var g_express = {},
                                //快递
                                g_express_info = {},
                                g_baseselobj = null,
                                g_curedittagflag = 0,
                                // g_tp_img = '',
                                g_evencastnum = 0,
                                g_permitopt = true; //模板标签参数
                            var g_mar = false;
                            var aDrag = false; //拉伸标志
                            var bDrag = false; //移动标志
                            var x, y, _x, _y, lx, ly, maxL, maxT, maxW, maxH, taghtmlstr;
                            $(function() {
                                if (!$scope.shopid) {
                                    // helper.myAlert('请先上传快递背景图,再添加要打印的选项');
                                    $('.edit-box').css("background-repeat", 'repeat');
                                }

                                if ($scope.shopid != 0) {
                                    $('.upload-img').css('display', 'none');
                                    $('#save-content, #print-view').show(); //b编辑需要的按钮
                                    $('#add-content, .temp-top').hide(); //隐藏添加按钮
                                } else {
                                    $('.upload-img').css('display', 'inline-block'); //显示上传背景图按钮
                                    $('#save-content, #print-view').hide();
                                    $('#add-content, .temp-top').show();
                                }

                                $('.upload-img').css('display', 'inline-block'); //显示上传背景图按钮

                                //打印--编辑模板--左侧打印项菜单
                                $('#main').on('click', '.ele-cat-title',
                                    function() {
                                        var obj = $(this).parent();
                                        var height = parseInt($(this).siblings('div').css('height'));
                                        var top = $(this).siblings('div').offset().top;
                                        if (obj.hasClass('open')) {
                                            obj.removeClass('open');
                                            obj.addClass('close');
                                        } else {
                                            obj.removeClass('close');
                                            obj.addClass('open');
                                        }
                                        $('.table-left').scrollTop($('.table-left')[0].scrollHeight);
                                    });
                                //标尺随着滚动条滚动
                                $('.prt-table-box .table-right').scroll(function() {
                                    var top = -$(this).scrollTop();
                                    var left = -$(this).scrollLeft();
                                    $('.prt-table-box .staff-y .for-position').css('top', top + 'px');
                                    $('.prt-table-box .staff-x .for-position').css('left', left + 'px');
                                });

                                $('#main').on('click', '.text-strong, .to-wrap',
                                    function() {
                                        if ($(this).hasClass('checked')) {
                                            $(this).removeClass('checked');
                                        } else {
                                            $(this).addClass('checked');
                                        }
                                    });
                                //控制按钮操作    加粗 删除
                                $('.ctrl-bar a').click(function() {
                                    if ($(this).hasClass("text-strong")) { //加粗
                                        if (!$(this).hasClass("checked")) {
                                            $('.selected').css('font-weight', 'bold');
                                        } else {
                                            $('.selected').css('font-weight', '');
                                        }
                                    } else if ($(this).hasClass("to-wrap")) { //可换行
                                        if (!$(this).hasClass("checked")) {
                                            $('.selected').css('white-space', 'normal');
                                        } else {
                                            $('.selected').css('white-space', 'nowrap');
                                        }
                                    } else if ($(this).hasClass("text-left")) {
                                        $('.selected').css('text-align', 'left');
                                    } else if ($(this).hasClass("text-center")) {
                                        $('.selected').css('text-align', 'center');
                                    } else if ($(this).hasClass("text-right")) {
                                        $('.selected').css('text-align', 'right');
                                    } else if ($(this).hasClass("delete")) { //删除
                                        if ($(".edit-box .selected").length == 0) {
                                            helper.myAlert('没有选中的标签!');
                                            return;
                                        }
                                        $(".edit-box .selected").each(function(index) {
                                            //变量标签才需要同步checkbox状态
                                            if (!$(this).hasClass('editable-ele')) {
                                                var tagname = $(this).attr("name");
                                                $('.prt-ele-list label[name="' + tagname + '"]').checkbox('uncheck');
                                            }

                                            if (!$(this).hasClass('item-table-ele')) {
                                                $(this).remove();
                                            }
                                        });
                                        $('.listenval').val('');
                                    } else if ($(this).hasClass("quote-all")) { //引用到全部
                                        var family = $('.ft-family ul .active').attr('name');
                                        if (family == undefined || family == '') {
                                            family = "宋体";
                                        }
                                        var size = $('#ex-size span').html();
                                        if (size == '字号') {
                                            size = "12px";
                                        }
                                        if ($('.ctrl-bar .text-strong').hasClass('checked')) {
                                            var bold = "bold";
                                        } else {
                                            var bold = "normal";
                                        }
                                        if ($('.ctrl-bar .to-wrap').hasClass('checked')) {
                                            var wrap = "normal"; //可换行
                                        } else {
                                            var wrap = "nowrap"; //不可换行
                                        }
                                        $('.edit-box .element').each(function() {
                                            $(this).css("font-family", family);
                                            $(this).css("font-size", size);
                                            $(this).css("font-weight", bold);
                                            $(this).css("white-space", wrap);
                                        });
                                    } else if ($(this).hasClass("reload")) { //重置
                                        if (!$scope.shopid) {
                                            helper.myAlert('还未保存模板不需要重置');
                                            return
                                        } else {
                                            $('#x_margin,#y_margin,#x_size,#y_size').val('');
                                            getExpressOne();
                                        }
                                    }
                                });

                                //设置字体
                                $('.table-right .ft-family li').click(function() {
                                    $('.ft-family li.active').removeClass('active');
                                    $(this).addClass('active');

                                    var fontfamily = $('.ft-family li.active a').text();
                                    $('.edit-box .selected').css('font-family', fontfamily);
                                });
                                //设置字号
                                $('.table-right .ft-size li').click(function() {
                                    $('.ft-size li.active').removeClass('active');
                                    $(this).addClass('active');
                                    var fsize = $('.ft-size li.active a').text();
                                    fsize = parseInt(fsize);
                                    $('.edit-box .selected').css('font-size', fsize);
                                    $('.edit-box .selected').css('line-height', fsize + 'px');
                                });
                                //回车改变坐标和尺寸
                                $('.ctrl-bar, .prt-top-form').on("keyup", 'input:not(.mod-name)',
                                    function(event) {
                                        // if (event.keyCode != 37 && event.keyCode != 39) {
                                        // $(this).val($(this).val().replace(/[^\d]/g, ''));
                                        // }
                                        if (event.keyCode == 13) {
                                            var curid = $(this).attr('id');
                                            var editval = parseInt(Trim($(this).val()));
                                            if (curid == 'x_margin') {
                                                $('.edit-box .selected').css("left", editval);
                                            } else if (curid == 'y_margin') {
                                                $('.edit-box .selected').css("top", editval);
                                            } else if (curid == 'x_size') {
                                                $('.edit-box .selected').css("width", editval);
                                            } else if (curid == 'y_size') {
                                                $('.edit-box .selected').css("height", editval);
                                            } else if (curid == 'x-size') { //模板尺寸
                                                $('.edit-box').css("width", parseInt(editval) * 4);
                                            } else if (curid == 'y-size') {
                                                $('.edit-box').css("height", parseInt(editval) * 4);
                                            }
                                        }
                                    });
                                //添加系统标签
                                $(document).on('click', '.ele-list a',
                                    function() {
                                        // var eleName = $(this).siblings('font').html();
                                        // console.log("eleName", eleName);
                                        // var id = $(this).attr('id');
                                        // console.log("idid", id);
                                        // taghtmlstr = MakeOnetagHtml(eleName, "0,0", 2, null, null, null, null, null, null, id);
                                        // $('.edit-box').append(taghtmlstr);
                                        // var newobj = $('.edit-box').children('div').last(); //获取刚添加的元素
                                        // removeFocusEle();
                                        // BoxFocus(newobj);
                                    });

                                //添加自定义标签
                                $('.add-custom-ele').click(function() {
                                    $('#confirmcontent').prop('value', "");
                                    $('#pop-add-newprint').modal('show');
                                });

                                //确定添加自定义打印项
                                // $(document).on('click', '#addprint_save',
                                //     function() {
                                //         var tagname = Trim($('#confirmcontent').prop('value'));
                                //         if (tagname == "") {
                                //             helper.myAlert('内容不能为空！');
                                //             return;
                                //         }
                                //         if (g_curedittagflag == 0) {
                                //             taghtmlstr = MakeOnetagHtml(tagname, "0,0", 1);
                                //             $('.edit-box').append(taghtmlstr);
                                //         } else {
                                //             $('.edit-box .selected').attr('name', tagname);
                                //             $('.edit-box .selected .for-overflow font').html(tagname);
                                //             g_curedittagflag = 0;
                                //         }
                                //         $('#pop-add-newprint').modal('hide');
                                //     });
                                //编辑自定义添加标签
                                $(document).on('click', '.selected .for-overflow .edit',
                                    function() {
                                        //if(g_permitopt){
                                        var tagname = $(this).siblings('font').html();
                                        g_curedittagflag = 1;
                                        $('#confirmcontent').prop('value', tagname);
                                        $('#pop-add-newprint').modal('show');
                                        //}
                                    });
                                //保存模板信息 / 另存为 /添加
                                $('#save-content, #saveothertpl, #add-content').on('click',
                                    function() {
                                        var clickName = $(this).attr('id');
                                        console.log("clickName", clickName);
                                        var tpname = $('#tmplate-name').val();
                                        var typeid = $(this).attr('id'); //添加
                                         // $scope.tep_type = 1 ;
                                        // var company = $.trim($('#wlList .active a').html());
                                        console.log("tpname", tpname, $scope.tpname);
                                        if ($scope.g_tp_img == '') {
                                            helper.myAlert("快递物流模板的背景图不能为空!");
                                            return;
                                        }

                                        if (typeid == 'add-content') {
                                            if (!$scope.shipping_corp) {
                                                helper.myAlert("物流名称不能为空!");
                                                return;
                                            }
                                        }
                                        if (!$scope.tpname) {
                                            helper.myAlert("模板名称不能为空!");
                                            return;
                                        }
                                        if ($scope.tpname.length > 15) {
                                            helper.myAlert("模板名称不能超过15个字!");
                                            return;
                                        }
                                        // var xoffset = $('#x-offset').val();
                                        // var yoffset = $('#y-offset').val();
                                        // var xsize = $('#x-size').val();
                                        // var ysize = $('#y-size').val();
                                        if ($scope.x_size == '' || $scope.y_size == '') {
                                            helper.myAlert("模板尺寸不能为空!");
                                            return;
                                        }
                                        if (isNaN($scope.x_size) || $scope.x_size < 0 || isNaN($scope.y_size) || $scope.y_size < 0) {
                                            helper.myAlert('模板尺寸必须是正整数');
                                            return false;
                                        }
                                        //是否打印logo-电子免单
                                        var printlogo = 0;
                                        if ($('.prt-logo').hasClass('checked')) {
                                            printlogo = 1;
                                        }
                                        //拼装对象结构
                                        var newtag = Makedom2fhtpobj();
                                        if (newtag.length <= 2) {
                                            helper.myAlert('模板内容不能为空！');
                                            return false;
                                        }

                                        // var data = $scope.tpldata ? $scope.tpldata : {};
                                        var data = {};
                                        data.name = $scope.tpname;
                                        data.xiaopiao_type = 'item';
                                        data.image = $scope.g_tp_img;
                                        data.size = $scope.x_size + 'x' + $scope.y_size;
                                        data.shipping_corp = $scope.shipping_corp;
                                        data.tep_type = 1;
                                        data.store_id = $rootScope.store_id;
                                        if ($scope.tpldata) {
                                            if ($scope.tpldata.print_id) {
                                                data.print_id = $scope.tpldata.print_id;
                                            }
                                            if ($scope.tpldata.print_pub_id) {
                                                data.print_pub_id = $scope.tpldata.print_pub_id;
                                            }
                                        }
                                        data.content = {
                                            // 'company': $scope.company,
                                            'value': newtag,
                                            'x_offset': $scope.x_offset,
                                            'y_offset': $scope.y_offset,
                                        }

                                        if ($scope.printPub) {
                                            data.type_id = 1;
                                            if ($scope.shopid) {
                                                dataService.printPubUpdate(data).then(function(result) {
                                                    if (result.print_pub_id) {
                                                        // $(window).unbind();
                                                        helper.myAlert("success", null, null, function() {
                                                            $state.go("dhfprint.list");
                                                        });
                                                    } else {
                                                        helper.myAlert("error" + result.Msg);
                                                    }
                                                });
                                            } else {
                                                data.status_id = 0;
                                                dataService.printPubAdd(data).then(function(result) {
                                                    if (result.print_pub_id) {
                                                        helper.myAlert("success", null, null, function() {
                                                            $state.go("dhfprint.list");
                                                        });
                                                    } else {
                                                        helper.myAlert("error" + result.Msg);
                                                    }
                                                });
                                            }
                                        } else {
                                            var getData = {
                                                query: {
                                                    shipping_corp: $scope.shipping_corp,
                                                    tep_type: $scope.tep_type,
                                                    store_id: $rootScope.store_id,
                                                }
                                            };
                                            $scope.getdftTmp(getData).then(function(re) {
                                                if (!re) {
                                                    data.default_template = 1;
                                                }
                                                dataService.printSellerUpdate(data).then(function(result) {
                                                    if (result.print_id) {
                                                        // $(window).unbind();
                                                        helper.myAlert("success", null, null, function() {
                                                            $state.go("print.list");
                                                        });
                                                    } else {
                                                        helper.myAlert("error" + result.Msg);
                                                    }
                                                });
                                            });

                                        }
                                    });

                                //预览
                                $('#print-view').on('click',
                                    function() {
                                        var expressEdit = Makedom2fhtpobj();
                                        g_express_info.size = $('#x-size').val() + 'x' + $('#y-size').val();
                                        g_express_info.value = expressEdit;

                                        setLocal('expressEdit', JSON.stringify(g_express_info));
                                        var w = $('#x-size').val();
                                        var h = $('#y-size').val();
                                        var g_server_iptest = document.location.hostname;
                                        QN.application.invoke({
                                            cmd: 'browserUrlEmbedded',
                                            //打开内部窗口
                                            param: {
                                                url: 'http://' + g_server_iptest + '/hntrade/pluginpc/dyfh_express_view_v3.php?userid=' + g_sellerid + '&tid=' + shopid,
                                                title: '预览快递单模板',
                                                //标题
                                                maximize: 'true',
                                                //是否显示最大化
                                                fixborder: 'true',
                                                //禁止拖拽
                                                width: parseInt(w) * 4,
                                                height: parseInt(h) * 4,
                                                refreshExisting: 'true' //是否刷新
                                            }
                                        });
                                    });

                                //空白处放弃选中状态
                                $('#main').on('click', '*',
                                    function(e) {
                                        if ($(this).hasClass('element') || $(this).hasClass('delete') || $(this).hasClass('ctrl-bar-btn') || $(this).hasClass('input-medium') || $(this).hasClass('sui-dropdown') || $(this).hasClass('sui-btn')) {
                                            g_evencastnum += 1;
                                        }
                                    });
                                //标签右上角编辑,删除
                                $(document).on('mousedown', '.edit, .delete',
                                    function() {
                                        g_permitopt = true;
                                    });
                                //删除标签
                                $(document).on('click', '.selected .for-overflow .delete',
                                    function() {
                                        //if(g_permitopt){
                                        var tagname = $(this).closest('.element').attr("name");
                                        if (!$(this).closest('.element').hasClass('editable-ele')) {
                                            $('.prt-ele-list label[name="' + tagname + '"]').checkbox('uncheck');
                                        }
                                        $(this).closest('.element').remove();
                                        //}
                                    });
                                //空白处放弃选中状态
                                $('#main').click(function() {
                                    if (g_evencastnum == 0) {
                                        removeFocusEle();
                                    } else {
                                        g_evencastnum = 0;
                                    }
                                });
                                /*框选=========================*/
                                if ($('.edit-box').offset()) {
                                    var bt = $('.edit-box').offset().top;
                                    var bl = $('.edit-box').offset().left;
                                    var g_curctrlbar = "br";
                                    $(window).resize(function() {
                                        bt = $('.edit-box').offset().top;
                                        bl = $('.edit-box').offset().left;
                                    });
                                    $(window).unbind();
                                } else {
                                    var bt;
                                    var bl;
                                    var g_curctrlbar = "br";
                                }

                                // console.log("$bt", bt, bl);
                                $('body').on('mousedown', '.canvas .edit-box',
                                    function() {
                                        if (!g_mar) {
                                            var e = event || window.event;
                                            x = e.pageX;
                                            y = e.pageY;
                                            var left = x - 197;
                                            var top = y + $('.table-right').scrollTop() - 108;
                                            $(this).append('<div class="marquee"></div>');
                                            $('.marquee').css({
                                                'left': left + 'px',
                                                'top': top + 'px'
                                            });
                                            g_mar = true;
                                        }
                                    });
                                $('body').on('mouseup', '.canvas .edit-box',
                                    function() {
                                        //计算框选范围
                                        var marobj = {};
                                        marobj.x = parseInt($('.marquee').css('left'));
                                        marobj.y = parseInt($('.marquee').css('top'));
                                        marobj.w = $('.marquee').width();
                                        marobj.h = $('.marquee').height();
                                        //....遍历所有元素
                                        if (marobj.w > 5 && marobj.h > 5) {
                                            Selelementbyrectangle(marobj);
                                        }
                                        $('.marquee').remove();
                                        g_mar = false;
                                    });
                                /*框选=========================*/
                                //方向移动键
                                $(document).on('keydown', '*',
                                    function(event) {
                                        // console.log("event", event);
                                        if ($(':focus').prop('tagName') == "INPUT" || $(':focus').prop('tagName') == "TEXTAREA") return true;
                                        if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                                            if ($(".edit-box .selected").length > 0) {
                                                $(".edit-box .selected").each(function() {
                                                    var diffx = 0,
                                                        diffy = 0;
                                                    if (event.keyCode == "37") { //left
                                                        diffx = -1;
                                                    } else if (event.keyCode == "38") { //up
                                                        diffy = -1;
                                                    } else if (event.keyCode == "39") { //right
                                                        diffx = 1;
                                                    } else if (event.keyCode == "40") { //down
                                                        diffy = 1;
                                                    }
                                                    if (canMoveMultiEle(diffx, diffy)) {
                                                        x = parseInt($(this).css('left')) + diffx;
                                                        y = parseInt($(this).css('top')) + diffy;

                                                        x = x < 0 ? 0 : x;
                                                        y = y < 0 ? 0 : y;

                                                        $(this).css({
                                                            'left': x + 'px',
                                                            'top': y + 'px'
                                                        });
                                                        $('#x_margin').val(x);
                                                        $('#y_margin').val(y);
                                                    }
                                                });
                                                return false;
                                            }
                                        }
                                        //event.stopPropagation();
                                    });

                                $(document).mousemove(function(event) {
                                    var e = event || window.event;
                                    var diffx, diffy;
                                    if (bDrag == true) {
                                        g_permitopt = false;

                                        diffx = e.pageX - bl - _x;
                                        diffy = e.pageY - bt - _y;

                                        if (canMoveMultiEle(diffx, diffy)) {
                                            $(".edit-box .selected").each(function() {
                                                // console.log("thisthis",this);
                                                maxL = $('.edit-box').width() - parseInt($(this).css('width')) - 2;
                                                maxT = $('.edit-box').height() - parseInt($(this).css('height')) - 2;

                                                x = parseInt($(this).css('left')) + diffx;
                                                y = parseInt($(this).css('top')) + diffy;
                                                x = x < 0 ? 0 : x;
                                                y = y < 0 ? 0 : y;
                                                $(this).css({
                                                    'left': x + 'px',
                                                    'top': y + 'px'
                                                });
                                            });
                                        }

                                        _x = e.pageX - bl;
                                        _y = e.pageY - bt;

                                        //显示坐标
                                        var x_margin = $('.edit-box .selected').css('left');
                                        $('#x_margin').val(x_margin.replace('px', ''));
                                        var y_margin = $('.edit-box .selected').css('top');
                                        $('#y_margin').val(y_margin.replace('px', ''));
                                    }
                                    if (aDrag == true) {
                                        calcposizeonmove(e);
                                        //显示坐标
                                        var x_margin = $('.edit-box .selected').css('left');
                                        $('#x_margin').val(x_margin.replace('px', ''));
                                        var y_margin = $('.edit-box .selected').css('top');
                                        $('#y_margin').val(y_margin.replace('px', ''));

                                    }

                                    if (!aDrag && !bDrag) {
                                        if (g_mar) {
                                            _x = e.pageX;
                                            _y = e.pageY;
                                            var width = _x - x;
                                            var height = _y - y;
                                            $('.marquee').css({
                                                'width': width + 'px',
                                                'height': height + 'px'
                                            }).show();
                                        }
                                    } else {
                                        if (g_mar) {
                                            g_mar = false;
                                        }
                                    }
                                }).mouseup(function() {
                                    aDrag = false;
                                    bDrag = false;
                                });
                                //选中标签 准备移动或拉伸
                                $('.edit-box').on('mousedown', '.element',
                                    function() {
                                        g_mar = false;
                                        if (aDrag) return;

                                        bDrag = true;

                                        //如果点的这ELEMENT就是选中额元素...则不做选中状态的变化，如果不是则弃选，并选中当前element
                                        if (!isSelelement(this)) {
                                            removeFocusEle();
                                            BoxFocus(this);
                                        } else {
                                            g_baseselobj = this;
                                            $('.edit-box .element').removeClass('focus');
                                            $(this).addClass('focus');
                                        }
                                        var e = event || window.event;
                                        _x = e.pageX - bl; //-parseInt($('.selected').css('left'));
                                        _y = e.pageY - bt; //-parseInt($('.selected').css('top'));
                                    });
                                //拉伸
                                $('.edit-box').on('mousedown', '.ele-tool-bar',
                                    function() {
                                        aDrag = true;
                                        bDrag = false;

                                        var pareobj = $(this).parent();

                                        var e = event || window.event;
                                        var clsname = $(this).prop("className");
                                        clsname = Trim(clsname.replace("ele-tool-bar", ''));
                                        g_curctrlbar = clsname;

                                        removeFocusEle();
                                        BoxFocus(pareobj);
                                    });
                                //根据模板id获取模板信息
                                if ($scope.shopid != 0) {
                                    getExpressOne();
                                } else {
                                    $scope.x_size = 210;
                                    $scope.y_size = 120;
                                }
                                //失去焦点改变模板大小
                                $scope.MbCc = function(curid) {
                                    if (curid == 'x_size') { //模板尺寸
                                        $('.edit-box').css("width", parseInt($scope.x_size) * 4);
                                    } else if (curid == 'y_size') {
                                        $('.edit-box').css("height", parseInt($scope.y_size) * 4);
                                    }
                                }
                                $scope.getdftTmp = function(getData) {
                                    return dataService.printSellerGet(getData).then(function(result) {
                                        if (result.prints) {
                                            return result.prints[0];
                                        } else {
                                            return false;
                                        }
                                    });
                                }
                                //拉伸不同位置计算出 宽高和位置
                                function calcposizeonmove(e) {
                                    var minw = 30,
                                        minh = 20,
                                        widhs = 0,
                                        height = 0,
                                        oldwidth = 0,
                                        oldheight = 0,
                                        oldtop, oldleft, newtop, newleft, curx, cury;

                                    oldwidth = $('.selected').width();

                                    oldheight = $('.selected').height();
                                    oldtop = parseInt($('.selected').css('top'));
                                    oldleft = parseInt($('.selected').css('left'));
                                    curx = e.pageX - bl;
                                    cury = e.pageY - bt;

                                    if (g_curctrlbar == "br") { //右下
                                        widhs = e.pageX - bl - parseInt($('.selected').css('left'));
                                        height = e.pageY - bt - parseInt($('.selected').css('top'));
                                        maxW = $('.edit-box').width() - parseInt($('.selected').css('left')) - 2;
                                        maxH = $('.edit-box').height() - parseInt($('.selected').css('top')) - 2;
                                        widhs = widhs < minw ? minw : widhs;
                                        widhs = widhs > maxW ? maxW : widhs;
                                        height = height < minh ? minh : height;
                                        height = height > maxH ? maxH : height;
                                        $('.selected').css({
                                            'width': widhs + 'px',
                                            'height': height + 'px'
                                        });
                                        $('#x_size').val(widhs);
                                        $('#y_size').val(height);
                                    } else if (g_curctrlbar == "bc") { //中下
                                        height = e.pageY - bt - parseInt($('.selected').css('top'));
                                        maxH = $('.edit-box').height() - parseInt($('.selected').css('top')) - 2;
                                        height = height < minh ? minh : height;
                                        height = height > maxH ? maxH : height;
                                        $('.selected').css({
                                            'height': height + 'px'
                                        });
                                        $('#y_size').val(height);
                                    } else if (g_curctrlbar == "bl") { //左下
                                        height = e.pageY - bt - parseInt($('.selected').css('top'));
                                        maxH = $('.edit-box').height() - parseInt($('.selected').css('top')) - 2;

                                        //XY坐标          
                                        newleft = e.pageX - bl;
                                        newleft = (newleft < 0) ? 0 : newleft;
                                        widhs = newleft - parseInt($('.selected').css('left'));

                                        widhs = -widhs;
                                        widhs = widhs + oldwidth;

                                        if (widhs > minw) {
                                            height = height < minh ? minh : height;
                                            $('.selected').css({
                                                'left': newleft + 'px',
                                                'width': widhs + 'px',
                                                'height': height + 'px'
                                            });
                                            $('#x_size').val(widhs);
                                            $('#y_size').val(height);
                                        }
                                    } else if (g_curctrlbar == "cl") { //左中
                                        //XY坐标          
                                        newleft = e.pageX - bl;
                                        newleft = (newleft < 0) ? 0 : newleft;
                                        widhs = newleft - parseInt($('.selected').css('left'));

                                        widhs = -widhs;
                                        widhs = widhs + oldwidth;
                                        if (widhs > minw) {
                                            $('.selected').css({
                                                'left': newleft + 'px',
                                                'width': widhs + 'px'
                                            });
                                        }
                                        if ($('.selected').hasClass('item-table-ele')) {
                                            var tblhei = $('.item-table-ele .prt-item-table').css('height');
                                            $('.item-table-ele').css('height', tblhei);
                                        }
                                        if (widhs < 0) {
                                            widhs = 0;
                                        }
                                        $('#x_size').val(widhs);
                                    } else if (g_curctrlbar == "tl") { //左上
                                        maxW = $('.edit-box').width() - parseInt($('.selected').css('left')) - 2;
                                        maxH = $('.edit-box').height() - parseInt($('.selected').css('top')) - 2;

                                        //XY坐标          
                                        newleft = e.pageX - bl;
                                        newleft = (newleft < 0) ? 0 : newleft;
                                        widhs = newleft - parseInt($('.selected').css('left'));

                                        widhs = -widhs;
                                        widhs = widhs + oldwidth;

                                        newtop = e.pageY - bt;
                                        newtop = (newtop < 0) ? 0 : newtop;
                                        height = newtop - parseInt($('.selected').css('top'));
                                        height = -height;
                                        height = height + oldheight;
                                        if (widhs <= minw && height <= minh) return;

                                        if (widhs <= minw) {
                                            $('.selected').css({
                                                'top': newtop + 'px',
                                                'height': height + 'px'
                                            });
                                        } else if (height <= minh) {
                                            $('.selected').css({
                                                'left': newleft + 'px',
                                                'width': widhs + 'px'
                                            });
                                        } else {
                                            $('.selected').css({
                                                'left': newleft + 'px',
                                                'top': newtop + 'px',
                                                'width': widhs + 'px',
                                                'height': height + 'px'
                                            });
                                        }
                                        $('#x_size').val(widhs);
                                        $('#y_size').val(height);
                                    } else if (g_curctrlbar == "tc") { //中上
                                        newtop = e.pageY - bt;
                                        newtop = (newtop < 0) ? 0 : newtop;
                                        height = newtop - parseInt($('.selected').css('top'));
                                        height = -height;
                                        height = height + oldheight;

                                        if (height <= minh) return;

                                        $('.selected').css({
                                            'top': newtop + 'px',
                                            'height': height + 'px'
                                        });
                                        $('#y_size').val(height);
                                    } else if (g_curctrlbar == "tr") { //右上
                                        widhs = e.pageX - bl - parseInt($('.selected').css('left'));
                                        maxW = $('.edit-box').width() - parseInt($('.selected').css('left')) - 2;

                                        widhs = widhs < minw ? minw : widhs;

                                        newtop = e.pageY - bt;
                                        newtop = (newtop < 0) ? 0 : newtop;
                                        height = newtop - parseInt($('.selected').css('top'));
                                        height = -height;
                                        height = height + oldheight;

                                        if (height <= minh) {
                                            $('.selected').css({
                                                'width': widhs + 'px'
                                            });
                                            return;
                                        }

                                        $('.selected').css({
                                            'top': newtop + 'px',
                                            'width': widhs + 'px',
                                            'height': height + 'px'
                                        });
                                        $('#x_size').val(widhs);
                                        $('#y_size').val(height);
                                    } else if (g_curctrlbar == "cr") { //右中
                                        widhs = e.pageX - bl - parseInt($('.selected').css('left'));
                                        maxW = $('.edit-box').width() - parseInt($('.selected').css('left')) - 2;

                                        widhs = widhs < minw ? minw : widhs;
                                        widhs = widhs > maxW ? maxW : widhs;
                                        $('.selected').css({
                                            'width': widhs + 'px'
                                        });

                                        if ($('.selected').hasClass('item-table-ele')) {
                                            var tblhei = $('.item-table-ele .prt-item-table').css('height');
                                            $('.item-table-ele').css('height', tblhei);
                                        }
                                        if (widhs < 0) {
                                            widhs = 0;
                                        }
                                        $('#x_size').val(widhs);
                                    }
                                }
                            });
                            //根据模板id获取模板信息
                            function getExpressOne() {
                                $('.edit-box .element').remove();
                                if ($scope.printPub) {
                                    dataService.printPubOne($scope.shopid).then(function(r) {
                                        if (r) {
                                            $scope.tpldata = r;
                                            if ($scope.tpldata.content) {
                                                // console.log("content", $scope.tpldata.content);
                                                AssemblyData();
                                            }
                                        }
                                    });
                                } else {
                                    dataService.printSellerOne($scope.shopid).then(function(r) {
                                        if (r) {
                                            $scope.tpldata = r;
                                            if ($scope.tpldata.content) {
                                                // console.log("valuevalue", $scope.tpldata.content);
                                                AssemblyData();
                                            }
                                        }
                                    });
                                }

                                function AssemblyData() {
                                    var g_express_info = JSON.parse($scope.tpldata.content);
                                    // var g_express_info = $scope.tpldata.content;
                                    if (g_express_info) {
                                        $('.custom-box').hide();
                                        console.log("g_express_info", g_express_info);
                                        $scope.shipping_corp = $scope.tpldata.shipping_corp;
                                        $scope.tep_type = $scope.tpldata.tep_type;
                                        $scope.tpname = g_express_info.tpname = $scope.tpldata.name;
                                        $scope.g_tp_img = g_express_info.image = $scope.tpldata.image;
                                        g_express_info.size = $scope.tpldata.size;
                                        var size = g_express_info.size.split('x');
                                        $('.edit-box').css('width', parseInt(size[0]) * 4);
                                        $('.edit-box').css('height', parseInt(size[1]) * 4);
                                        $('.custom-box').css('width', parseInt(size[0]) * 4);
                                        $('.custom-box').css('height', parseInt(size[1]) * 4);
                                        // //偏移量
                                        // $('#x-offset').val(row.x_margin);
                                        // $('#y-offset').val(row.y_margin);
                                        // //模板尺寸
                                        // $('#x-size').val(size[0]);
                                        // $('#y-size').val(size[1]);
                                        // $('#tmplate-name').val(g_express_info['tpname']);
                                        // console.log("g_express_info.value", g_express_info.value);
                                        $scope.x_size = size[0];
                                        $scope.y_size = size[1];
                                        $scope.x_offset = g_express_info.x_offset;
                                        $scope.y_offset = g_express_info.y_offset;

                                        // $scope.g_tp_img = g_express_info['img'];
                                        $('.canvas .edit-box').css('background-size', '100% 100%');
                                        $('.canvas .edit-box').css('background-image', 'url(' + decodeURIComponent($scope.g_tp_img) + ')');
                                        if (g_express_info.value != '') {
                                            g_express = JSON.parse(g_express_info.value);
                                            jsonParse();
                                        }
                                        // $('.addWlName').html(g_express_info.company);
                                    } else {
                                        helper.myAlert("没有找到模板");
                                    }
                                }
                            }

                            function Trim(str) {
                                if (str != "") return str.trim();
                                else return str
                            }

                            //解析模板参数
                            function jsonParse() {
                                console.log("g_express", g_express);
                                for (var i = 0; i < g_express.length; i++) {
                                    var possize = g_express[i]['left'] + ',' + g_express[i]['top'] + ',' + g_express[i]['width'] + ',' + g_express[i]['height'];
                                    var taghtmlstr = MakeOnetagHtml(g_express[i]['name'], possize, 3, g_express[i]['font-family'], g_express[i]['font-size'], g_express[i]['font-weight'], g_express[i]['white-space'], g_express[i]['img'], g_express[i]['flg'], g_express[i]['id']);
                                    console.log(taghtmlstr);
                                    $('.edit-box').append(taghtmlstr);
                                }
                            }

                            // //生成标签html结构 名字 坐标 宽高 type 1-自定义标签 2-变量 flg  是否是自定义标签
                            // function MakeOnetagHtml(name, possize, type, family, size, weight, space, imgurl, flg, id) {
                            //     var htmlstr = "",
                            //         stylestr = "",
                            //         cls = "";
                            //     var posobj = ParePossize(possize);
                            //     var picurl = imgurl;
                            //     //根据不同类型 拼装标签的  html结构...
                            //     var y = 0;
                            //     stylestr = 'left:' + posobj.x + 'px;top:' + posobj.y + 'px';
                            //     //有宽高
                            //     if (posobj.width != undefined) {
                            //         stylestr += ';width:' + posobj.width + "px;height:" + posobj.height + "px";
                            //     }
                            //     //有字体样式
                            //     if (family != undefined) {
                            //         stylestr += ';font-family:' + family;
                            //     }
                            //     //字体大小
                            //     if (size != undefined) {
                            //         stylestr += ';font-size:' + size;
                            //     }
                            //     //字体加粗
                            //     if (weight != undefined) {
                            //         stylestr += ';font-weight:' + weight;
                            //     }


                            //     //字体换行
                            //     if (space != undefined) {
                            //         stylestr += ';white-space:' + space;
                            //     } else {
                            //         stylestr += ';white-space:normal'; //可换行
                            //     }

                            //     if (type == 1 || type == 5) { //自定义标签 可编辑
                            //         cls += 'editable-ele';
                            //     }
                            //     if (flg != undefined) {
                            //         cls += 'editable-ele';
                            //     }

                            //     stylestr += ';line-height:normal;';
                            //     console.log("stylestr",stylestr,id);
                            //     htmlstr += '<div class="element ' + cls + '" style="' + stylestr + '" id="' + id + '">';
                            //     htmlstr += '<div class="for-overflow">';
                            //     htmlstr += '<font>' + name + '</font>';
                            //     if (type == 1 || flg != undefined || type == 5) { //自定义标签 可编辑
                            //         htmlstr += '<a class="edit"></a>';
                            //     }
                            //     htmlstr += '<a class="delete"></a>';
                            //     htmlstr += '</div>';
                            //     htmlstr += '</div>';
                            //     console.log("htmlstr",htmlstr);
                            //     return htmlstr;
                            // }
                            //添加选中样式
                            function BoxFocus(ev) {
                                var ctrlbarhtml = "";
                                $(ev).addClass('selected');
                                ctrlbarhtml += '<span class="ele-tool-bar tl"></span>';
                                ctrlbarhtml += '<span class="ele-tool-bar tc"></span>';
                                ctrlbarhtml += '<span class="ele-tool-bar tr"></span>';
                                ctrlbarhtml += '<span class="ele-tool-bar cl"></span>';
                                ctrlbarhtml += '<span class="ele-tool-bar cr"></span>';
                                ctrlbarhtml += '<span class="ele-tool-bar bl"></span>';
                                ctrlbarhtml += '<span class="ele-tool-bar bc"></span>';
                                ctrlbarhtml += '<span class="ele-tool-bar br"></span>';
                                $(ev).append(ctrlbarhtml);
                                displayDefaultTag();
                            }
                            //填充默认值
                            function displayDefaultTag() {
                                var family = $('.edit-box .selected').css('font-family');
                                if (family == undefined || family == '' || family.indexOf(',') > 0) {
                                    family = '宋体';
                                }
                                //字体
                                $('#ex-family span').html(family);
                                $('.ft-family ul .active').removeClass('active');
                                $('.ft-family li[name="' + family + '"]').addClass('active');

                                //字号
                                var size = $('.edit-box .selected').css('font-size');
                                if (size == undefined || size == '') {
                                    size = 12;
                                }
                                size = size.replace("px", '');
                                $('#ex-size span').html(size + 'px');
                                $('.ft-size ul .active').removeClass('active');
                                $('.ft-size li a[value="' + size + '"]').parent().addClass('active');
                                //是否加粗
                                var bold = $('.edit-box .selected').css('font-weight');
                                if (bold == 'bold') {
                                    $('.ctrl-bar .text-strong').addClass('checked');
                                } else {
                                    $('.ctrl-bar .text-strong').removeClass('checked');
                                }
                                //是否换行
                                var space = $('.edit-box .selected').css('white-space');
                                if (space == 'nowrap') {
                                    $('.ctrl-bar .to-wrap').removeClass('checked');
                                } else {
                                    $('.ctrl-bar .to-wrap').addClass('checked');
                                }

                                //显示坐标
                                var x_margin = $('.edit-box .selected').css('left');
                                $('#x_margin').val(x_margin.replace('px', ''));
                                var y_margin = $('.edit-box .selected').css('top');
                                $('#y_margin').val(y_margin.replace('px', ''));
                                //显示尺寸
                                var x_size = $('.edit-box .selected').css('width');
                                $('#x_size').val(x_size.replace('px', ''));
                                var y_size = $('.edit-box .selected').css('height');
                                $('#y_size').val(y_size.replace('px', ''));
                            }

                            function canMoveMultiEle(diffx, diffy) {
                                var re = true;
                                $(".edit-box .selected").each(function() {
                                    maxL = $('.edit-box').width() - parseInt($(this).css('width')) - 2;
                                    maxT = $('.edit-box').height() - parseInt($(this).css('height')) - 2;
                                    x = parseInt($(this).css('left')) + diffx;
                                    y = parseInt($(this).css('top')) + diffy;
                                    var maxY = 0;
                                    if (x < 0 || y < maxY || x > maxL || y > maxT) {
                                        re = false;
                                    }
                                });
                                return re;
                            }
                            //添加样式
                            $scope.adddataStyle = function($event) {
                                var then = $event.target;
                                var eleName = $(then).siblings('font').html();
                                // console.log("thisthis", then);
                                var id = $(then).attr('id');
                                // console.log("idid", id);
                                taghtmlstr = MakeOnetagHtml(eleName, "0,0", 2, null, null, null, null, null, null, id);
                                console.log("taghtmlstr", taghtmlstr);
                                $('.edit-box').append(taghtmlstr);
                                var newobj = $('.edit-box').children('div').last(); //获取刚添加的元素
                                removeFocusEle();
                                BoxFocus(newobj);
                            }
                            //添加自定义
                            $scope.adddataStylezdy = function($event) {
                                // var tagname = Trim($('#confirmcontent').prop('value'));
                                if ($scope.zdyconten == "") {
                                    helper.myAlert('内容不能为空！');
                                    return;
                                }
                                console.error("", $scope.zdyconten, g_curedittagflag);
                                if (g_curedittagflag == 0) {
                                    taghtmlstr = MakeOnetagHtml($scope.zdyconten, "0,0", 1);
                                    $('.edit-box').append(taghtmlstr);
                                } else {
                                    $('.edit-box .selected').attr('name', $scope.zdyconten);
                                    $('.edit-box .selected .for-overflow font').html($scope.zdyconten);
                                    g_curedittagflag = 0;
                                }
                                $('#pop-add-newprint').modal('hide');
                            }
                            $scope.addhtml = function() {
                                $scope.tmphtml = '';
                                $('#pop-add-newprint-html').modal('show');
                            }
                            $scope.allrem = function() {
                                // console.error($(".edit-box"));return;
                                $(".edit-box .element").each(function(index) {
                                    $(this).remove();
                                });
                                $('.listenval').val('');
                            }
                            $scope.additem = function(itemhtml) {
                                if ($scope.tmphtml) {
                                    console.error("1111111111111111", itemhtml);
                                    // var itemhtml = '<div class="element editable-ele" style="left:9px;top:212px;width:53px;height:25px;font-family:宋体;font-size:12px;font-weight:normal;white-space:normal;line-height:normal;position: absolute" id="zdy"><div class="for-overflow"><font>商品名称</font><a class="edit"></a><a class="delete"></a></div></div><div class="element editable-ele" style="left:71px;top:209px;width:52px;height:27px;font-family:宋体;font-size:12px;font-weight:normal;white-space:normal;line-height:normal;position: absolute" id="zdy"><div class="for-overflow"><font>数量</font><a class="edit"></a><a class="delete"></a></div></div><div class="element editable-ele" style="left:132px;top:208px;width:67px;height:28px;font-family:宋体;font-size:12px;font-weight:normal;white-space:normal;line-height:normal;position: absolute" id="zdy"><div class="for-overflow"><font>价格</font><a class="edit"></a><a class="delete"></a></div></div><div class="element" style="left: 29px; top: 242px; width: 110px; height: 20px; white-space: normal; line-height: normal; position: absolute;" id="item"><div class="for-overflow"><font>商品信息</font><a class="delete"></a></div></div>'
                                    $('.edit-box').append($scope.tmphtml);
                                }
                                $('#pop-add-newprint-html').modal('hide');
                            }

                            function isSelelement(curobj) {
                                var re = false;
                                if ($(curobj).hasClass('selected')) {
                                    re = true;
                                }
                                return re;
                            }
                            //拉选元素
                            function Selelementbyrectangle(marobj) {
                                removeFocusEle();

                                $(".edit-box .element").each(function(index) {
                                    var eleobj = {};
                                    eleobj.x = parseInt($(this).css('left'));
                                    eleobj.y = parseInt($(this).css('top'));
                                    eleobj.w = $(this).width();
                                    eleobj.h = $(this).height();

                                    //是否相交
                                    if (isrectcross(marobj, eleobj)) {
                                        BoxFocus(this);
                                        if (g_baseselobj == null) {
                                            g_baseselobj = this;
                                            $('.edit-box .element').removeClass('focus');
                                            $(this).addClass('focus');
                                        }
                                    }
                                });
                            }
                            //取绝对值
                            function _abs(val) {
                                return (val < 0) ? -val : val;
                            }

                            /* 判断两个矩形是否相交*/
                            function isrectcross(ra, rb) {
                                var a_cx, a_cy;
                                /* 第一个中心点*/
                                var b_cx, b_cy;
                                /* 第二个中心点*/

                                a_cx = ra.x + (ra.w / 2);
                                a_cy = ra.y + (ra.h / 2);

                                b_cx = rb.x + (rb.w / 2);
                                b_cy = rb.y + (rb.h / 2);
                                return ((_abs(a_cx - b_cx) <= (ra.w / 2 + rb.w / 2)) && (_abs(a_cy - b_cy) <= (ra.h / 2 + rb.h / 2)));
                            }
                            //弃选元素
                            function removeFocusEle() {
                                $('.element').removeClass('selected');
                                $('.edit-box .element').removeClass('focus');

                                $('.ele-tool-bar').remove();
                                $('.listenval').val('');
                                g_baseselobj = null;
                            }

                            //根据坐标字符串 解析成 位置对象 
                            function ParePossize(possize) {
                                var posobj = {
                                    'x': 0,
                                    'y': 0,
                                    'width': 110,
                                    'height': 20
                                };
                                var arrpos = possize.split(',');
                                if (arrpos[0] != undefined) {
                                    if (arrpos[0].indexOf('px') > 0) {
                                        posobj.x = arrpos[0].replace('px', '');
                                    } else {
                                        posobj.x = arrpos[0];
                                    }
                                }
                                if (arrpos[1] != undefined) {
                                    if (arrpos[1].indexOf('px') > 0) {
                                        posobj.y = arrpos[1].replace('px', '');
                                    } else {
                                        posobj.y = arrpos[1];
                                    }
                                }
                                if (arrpos[2] != undefined) {
                                    if (arrpos[2].indexOf('px') > 0) {
                                        posobj.width = arrpos[2].replace('px', '');
                                    } else {
                                        posobj.width = arrpos[2];
                                    }
                                }
                                if (arrpos[3] != undefined) {
                                    if (arrpos[3].indexOf('px') > 0) {
                                        posobj.height = arrpos[3].replace('px', '');
                                    } else {
                                        posobj.height = arrpos[3];
                                    }
                                }
                                return posobj;
                            }
                            //根据dom结构生成 快递模板对象
                            function Makedom2fhtpobj() {
                                //初始化发货模板对象
                                var tag = [];
                                $(".edit-box div.element").each(function(index) {
                                    var width = $(this).css('width');
                                    var height = $(this).css('height');
                                    var left = $(this).css('left');
                                    var top = $(this).css('top');
                                    var family = $(this).css('font-family');
                                    var size = $(this).css('font-size');
                                    var bold = $(this).css('font-weight');
                                    var wrap = $(this).css('white-space');
                                    var img = $(this).css('background-image');
                                    var id = $(this).attr("id");
                                    if (img != 'none') { //图片
                                        var name = $(this).attr('name');
                                        var imgurl = img;
                                    } else {
                                        var name = $(this).find('font').html();
                                        var imgurl = 'none';
                                    }
                                    if (family.indexOf(',') > 0) {
                                        family = '宋体';
                                    }
                                    if (bold != 'bold') {
                                        bold = 'normal';
                                    }
                                    tag.push({
                                        'name': name,
                                        'width': width,
                                        'height': height,
                                        'left': left,
                                        'top': top,
                                        'font-family': family,
                                        'font-size': size,
                                        'font-weight': bold,
                                        'white-space': wrap,
                                        'background-image': imgurl,
                                        'line-height': 'normal',
                                        'id': id,
                                    });
                                    //自定义标签
                                    if ($(this).hasClass('editable-ele')) {
                                        tag[index]['flg'] = 1;
                                    }
                                    console.log("id", id);
                                });
                                console.log("tag", tag);
                                return JSON.stringify(tag);
                            }
                        }

                        $timeout(function() {
                            if ($scope.shopid || $scope.printPub) {
                                $scope.init();
                            }
                        });

                        $scope.getImage = function(print) {
                            // console.log("printprint",print);
                            $scope.g_tp_img = print;
                            // $(this).removeClass('background-image').addClass('classB');
                            $('.canvas .edit-box').css('background-image', 'url()');
                            $('.canvas .edit-box').css('background-size', '100% 100%');
                            $('.canvas .edit-box').css('background-image', 'url(' + decodeURIComponent($scope.g_tp_img) + ')');
                            $('.canvas .edit-box').css('backgroundSize', "'" + $scope.sx_size + "" + $scope.sy_size + "'");
                        }
                        //删除背景图
                        $scope.delupImg = function() {
                            if ($scope.g_tp_img) {
                                $('.canvas .edit-box').css('background-image', 'url()');
                                $scope.g_tp_img = '';
                            }
                        }
                    }
                ],

                link: function(scope, element, attrs, ctrl) {

                }
            }
        })

        // printer-xiaopao
        .run(["$templateCache", "dataService", function($templateCache, dataService) {
            var tplName = "views/directives.printerxiaopao.html";
            dataService.tpl(tplName).then(function(html) {
                $templateCache.put(tplName, html);
            });
        }])
        //获取公共模板
        .directive('printerXiaopao', function($templateCache) {
            return {
                restrict: 'E',
                scope: {
                    shopid: '@',
                    printPub: '@',
                },
                template: $templateCache.get("views/directives.printerxiaopao.html"),
                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout', 'helper', '$state',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout, helper, $state) {
                        $scope.init = function() {
                            console.error("shopid", $scope.shopid);
                            if ($scope.shopid) {
                                $scope.getData();
                            } else {
                                $scope.articles = [{ id: "sender_name", name: "发件人-姓名" },
                                    { id: "sender_phone", name: "发件人-手机" },
                                    { id: "sender_address", name: "发件人-地址" },
                                    { id: "datatime", name: "发件日期" },
                                    { id: "store_name", name: "店铺名称" },
                                    { id: "receiver_time", name: "提货时间" },
                                ];
                            }

                            $scope.titleList = [{
                                    name: "卖家信息",
                                    list: [{ id: "sender_name", name: "发件人-姓名" },
                                        { id: "sender_phone", name: "发件人-手机" },
                                        { id: "sender_address", name: "发件人-地址" },
                                        { id: "datatime", name: "发件日期" },
                                        { id: "store_name", name: "店铺名称" },
                                    ]
                                },
                                {
                                    name: "买家信息",
                                    list: [{ id: "sender_name", name: "发件人-姓名" },
                                        { id: "", name: "" },
                                    ]
                                },
                                {
                                    name: "订单信息",
                                    list: [{ id: "sender_name", name: "发件人-姓名" },
                                        { id: "", name: "" },
                                    ]
                                },
                            ];
                            $(function() {
                                // nav收缩展开
                                $('.navMenu li a').on('click', function() {
                                    var parent = $(this).parent().parent(); //获取当前页签的父级的父级
                                    var labeul = $(this).parent("li").find(">ul")
                                    if ($(this).parent().hasClass('open') == false) {
                                        //展开未展开
                                        parent.find('ul').slideUp(300);
                                        parent.find("li").removeClass("open")
                                        parent.find('li a').removeClass("active").find(".arrow").removeClass("open")
                                        $(this).parent("li").addClass("open").find(labeul).slideDown(300);
                                        $(this).addClass("active").find(".arrow").addClass("open")
                                    } else {
                                        $(this).parent("li").removeClass("open").find(labeul).slideUp(300);
                                        if ($(this).parent().find("ul").length > 0) {
                                            $(this).removeClass("active").find(".arrow").removeClass("open")
                                        } else {
                                            $(this).addClass("active")
                                        }
                                    }

                                });
                            });

                        };
                        //选择操作
                        $scope.ChoiceTp = function(value) {
                            if (value) {
                                $scope.ckdata = value;
                            }
                        }
                        //请求数据
                        $scope.getData = function(pageNo) {
                            var api;
                            if ($scope.printPub) {
                                api = "printPubOne";
                            } else {
                                api = "printSellerOne";
                            }
                            return dataService[api]($scope.shopid).then(function(list) {
                                if (list) {
                                    $scope.printlist = list;
                                    $scope.name = $scope.printlist.name;
                                    var con = JSON.parse($scope.printlist.content);
                                    if (con) {
                                        if (con.value) {
                                            con = JSON.parse(con.value);
                                        }
                                        console.error("concon", con);
                                        $scope.articles = con;
                                    }
                                    $scope.shipping_corp = $scope.printlist.shipping_corp;
                                    $scope.xiaopiao_type = $scope.printlist.xiaopiao_type;
                                }
                            });
                        }

                        //清空模板
                        $scope.Delete = function() {
                            helper.myConfirm('确认清空模板吗？', function() {
                                $timeout(function() {
                                    $scope.articles = [];
                                }, 1000);
                            });
                        }

                        $scope.customPopup = function(value) {
                            $scope.custom = value ? value.name : '';
                            $.alert({
                                backdrop: "static",
                                keyboard: true,
                                // bgcolor: "rgb(0,0,0,0.9)",
                                title: '<span >自定义文字</span>',
                                body: '<div class="sui-form form-horizontal"> <div class="control-group"><label class="control-label v-top"> 文字内容:</label><div class="controls"><textarea rows="3" ng-model="custom" class="input-xlarge"></textarea></div></div></div>',
                                okBtn: '{{"确定"|translate}}',
                                closeBtn: true,
                                transition: true,
                                width: 'small',
                                show: function(e) {

                                    $compile($(e.currentTarget).contents())($scope);
                                },
                                okHide: function(e) {
                                    console.error($scope.custom, value);
                                    if (!value) {
                                        $scope.addcustomtitle();
                                    } else {
                                        _.map($scope.articles, function(aa, kk) {
                                            if (aa.$$hashKey == value.$$hashKey) {
                                                aa.name = $scope.custom;
                                            }
                                        });
                                    }
                                },
                            });
                        }
                        //添加自定义文字
                        $scope.addcustomtitle = function() {
                            if ($scope.custom) {
                                $timeout(function() {
                                    $scope.articles.push({
                                        name: $scope.custom,
                                        id: 'zdy',
                                    });
                                    // console.error("1111111111111111111111", $scope.custom, $scope.articles);
                                }, 1000)
                            }
                        }
                        //添加数据
                        $scope.adddataStyle = function($event) {
                            $scope.articles.push({
                                name: $event.currentTarget.innerText,
                                id: $event.currentTarget.id,
                            });
                            // console.error("$scope.articles", $scope.articles, $event);
                        }
                        //保存
                        $scope.save = function() {
                            var data = {};
                            data.name = $scope.name;
                            data.size = '57x120';
                            data.shipping_corp = $scope.shipping_corp;
                            data.xiaopiao_type = $scope.xiaopiao_type;
                            data.tep_type = 2;
                            console.error(" $scope.articles", $scope.articles);
                            console.error(" $scope.articles", $scope.articles);
                            data.content = $scope.articles;
                            data.type_id = 1;
                            if ($scope.printPub) {
                                if ($scope.shopid) {
                                    data.print_pub_id = $scope.shopid;
                                    dataService.printPubUpdate(data).then(function(result) {
                                        if (result.print_pub_id) {
                                            helper.myAlert("success", null, null, function() {
                                                $state.go("dhfprint.list");
                                            });
                                        } else {
                                            helper.myAlert("error" + result.Msg);
                                        }
                                    });
                                } else {
                                    data.status_id = 0;
                                    dataService.printPubAdd(data).then(function(result) {
                                        if (result.print_pub_id) {
                                            helper.myAlert("success", null, null, function() {
                                                $state.go("dhfprint.list");
                                            });
                                        } else {
                                            helper.myAlert("error" + result.Msg);
                                        }
                                    });
                                }
                            } else {
                                data.print_id = $scope.shopid;
                                data.store_id = $rootScope.store_id;
                                var getData = {
                                    query: {
                                        shipping_corp: $scope.shipping_corp,
                                        tep_type: 2,
                                        store_id: $rootScope.store_id,
                                    }
                                };
                                $scope.getdftTmp(getData).then(function(re) {
                                    if (!re) {
                                        data.default_template = 1;
                                    }
                                    dataService.printSellerUpdate(data).then(function(result) {
                                        if (result.print_id) {
                                            // $(window).unbind();
                                            helper.myAlert("success", null, null, function() {
                                                $state.go("print.list");
                                            });
                                        } else {
                                            helper.myAlert("error" + result.Msg);
                                        }
                                    });
                                });

                            }
                        }
                        $scope.getdftTmp = function(getData) {
                            return dataService.printSellerGet(getData).then(function(result) {
                                if (result.prints) {
                                    return result.prints[0];
                                } else {
                                    return false;
                                }
                            });
                        }
                        $scope.init();
                    }
                ],
                link: function(scope, element, attrs, ctrl) {}
            }
        })
        .run(["$templateCache", "dataService", function($templateCache, dataService) {
            var tplName = "views/directives.printtemplate.html";
            dataService.tpl(tplName).then(function(html) {
                $templateCache.put(tplName, html);
            });
        }])
        //获取公共模板
        .directive('printTemplate', function($templateCache) {
            return {
                restrict: 'E',
                // require: 'ngModel',
                scope: {
                    typeid: '@',
                    clallback: "&",
                },
                template: $templateCache.get("views/directives.printtemplate.html"),
                controller: ['$templateCache', '$rootScope', '$scope', '$compile', 'dataService', '$timeout', 'helper',
                    function($templateCache, $rootScope, $scope, $compile, dataService, $timeout, helper) {

                        //请求数据
                        $scope.pageData = function(pageNo) {
                            $scope.chosedType = $scope.chosedType ? $scope.chosedType : "express";
                            if ($scope.chosedType == 'express') {
                                $scope.tep_type = 1;
                            }
                            if ($scope.chosedType == 'xiaopao') {
                                $scope.tep_type = 2;
                            }

                            var query = { page_no: pageNo ? pageNo : "1", page_size: 20, status_id: 1, query: { tep_type: $scope.tep_type } };
                            return dataService.printPubGet(query).then(function(list) {
                                if (list.prints.length > 0) {
                                    $scope.printlist = list.prints;
                                    $scope.print_pub_id = $scope.printlist[0].print_pub_id;
                                    $scope.tpname = $scope.printlist[0].name;
                                    $scope.size = $scope.printlist[0].size;
                                    $scope.image = $scope.printlist[0].image;
                                    // $scope.content = JSON.parse($scope.printlist[0].content);
                                    // console.error("$scope.content",$scope.content);
                                    $scope.shipping_corp = $scope.printlist[0].shipping_corp;
                                    if ($scope.tep_type == 1) {
                                        $scope.content = JSON.parse($scope.printlist[0].content);
                                        $scope.getHtml();
                                    }
                                    if ($scope.tep_type == 2) {
                                        $scope.content = JSON.parse($scope.printlist[0].content);
                                    }
                                }
                            });
                        }

                        //选择模板
                        $scope.ChoiceTp = function(pub_id) {
                            if (pub_id) {
                                $scope.print_pub_id = pub_id;
                                console.log("pub_id", pub_id);
                                _.map($scope.printlist, function(print, key) {
                                    if (print.print_pub_id == pub_id) {
                                        $scope.tpname = print.name;
                                        $scope.size = print.size;
                                        $scope.image = print.image;
                                        $scope.content = JSON.parse(print.content);
                                        $scope.shipping_corp = print.shipping_corp;
                                        $scope.xiaopiao_type = print.xiaopiao_type;
                                        if ($scope.tep_type == 1) {
                                            $scope.getHtml();
                                        }
                                    }
                                });
                            }
                        }
                        //转换为html格式展示
                        $scope.getHtml = function() {
                            var g_express = JSON.parse($scope.content.value);
                            var size = $scope.size.split('x');
                            $scope.wid = parseInt(size[0]) * 4 + 'px';
                            $scope.hei = parseInt(size[1]) * 4 + 'px';
                            // console.error("g_express", g_express,$scope.width);
                            $(".element ").remove();
                            for (var i = 0; i < g_express.length; i++) {
                                var possize = g_express[i]['left'] + ',' + g_express[i]['top'] + ',' + g_express[i]['width'] + ',' + g_express[i]['height'];
                                var taghtmlstr = MakeOnetagHtml(g_express[i]['name'], possize, 3, g_express[i]['font-family'], g_express[i]['font-size'], g_express[i]['font-weight'], g_express[i]['white-space'], g_express[i]['img'], g_express[i]['flg'], g_express[i]['id'], 1);
                                // console.log("taghtmlstr", taghtmlstr);
                                $('.content').append(taghtmlstr);
                            }
                        }

                        //添加数据
                        $scope.addData = function($event) {
                            if ($scope.size && $scope.typeid && $scope.tpname && $scope.content) {
                                var data = {
                                    size: $scope.size,
                                    type_id: 1,
                                    name: $scope.tpname,
                                    image: $scope.image,
                                    content: $scope.content,
                                    tep_type: $scope.tep_type,
                                    store_id: $rootScope.store_id,
                                    shipping_corp: $scope.shipping_corp,
                                    xiaopiao_type: $scope.xiaopiao_type
                                };
                                if ($scope.image) {
                                    data.image = $scope.image;
                                }
                                $timeout(function() {
                                    // helper.myTip("保存中,请勿操作!", $event.currentTarget, null, 10);
                                    //查询有没有设置默认物流公司
                                    dataService.printSellerGet({ query: { 'default_express': 1, store_id: $rootScope.store_id } }).then(function(r) {
                                        if (r.prints.length <= 0) {
                                            //设置默认快递公司
                                            data.default_express = 1;
                                        }
                                        //c查询没有设置默认模板
                                        dataService.printSellerGet({ query: { 'shipping_corp': $scope.shipping_corp, "default_template": 1, store_id: $rootScope.store_id } }).then(function(rs) {
                                            if (rs.prints.length <= 0) {
                                                //设置默认模板
                                                data.default_template = 1;
                                            }
                                            dataService.printSellerAdd(data).then(function(r) {
                                                if (!r.Msg) {
                                                    $('#add-temp').modal('hide');
                                                    helper.myAlert('success', null, null, function() {
                                                        $scope.clallback({ typeid: $scope.typeid });
                                                    });
                                                } else {
                                                    // helper.myAlert('error'+r.Msg);
                                                    helper.myAlert('error' + r.Msg, null, null, function() {
                                                        $state.go("print.list");
                                                    });
                                                }
                                            });
                                        });
                                    });
                                });

                            } else {
                                helper.myAlert('请选择快递模板，在进行保存！');
                            }

                        }

                        $scope.pageData();
                    }
                ],
                link: function(scope, element, attrs, ctrl) {}
            }
        })
        //打印机列表 旧
        .directive('printerList', ['dataService', '$compile', 'helper', '$timeout', 'dhfprinterService',
            function(dataService, $compile, helper, $timeout, dhfprinterService) {
                return {
                    restrict: 'EA',
                    require: 'ngModel',
                    scope: {
                        ngModel: '=',
                        // printer: "=",
                    },

                    template: '<span><select ng-model="printer"   ng-options="option.name for option in printers track by option.name" ng-selected="tmpNgModel.name==option.name"></select></span>',
                    // template: '<span><span></span>',
                    controller: ['$templateCache', '$rootScope', '$scope',
                        function($templateCache, $rootScope, $scope) {
                            $scope.printers = {};

                            $scope.initData = function() {
                                $scope.printers = {};
                                dhfprinterService.getPrinters().then(function(a) {
                                    console.log("返回结果：", a);
                                    var x = _.values(a.msg);
                                    $scope.printers = x;
                                    $timeout(function() {
                                        if ($scope.ngModel) {
                                            _.map($scope.printers, function(da, k) {
                                                if ($scope.ngModel == da.name) {
                                                    $scope.printer = da;
                                                }
                                            });
                                        } else {
                                            $scope.printer = $scope.printers[0];
                                            $scope.ngModel = $scope.printer.name;
                                        }
                                    });
                                });
                            }
                            $scope.initData();
                        }
                    ],

                    link: function(scope, element, attrs, ctrl) {

                        ctrl.$render = function() {
                            if (ctrl.$viewValue) {
                                scope.ngModel = ctrl.$viewValue;
                                scope.initData();
                            }
                        };

                        scope.$watch('printer', function(newValue, oldValue, scope) {
                            if (newValue && newValue.name) {
                                ctrl.$setViewValue(newValue.name);
                            }
                        });
                    }
                }
            }
        ])

        //获取快递公司
        .directive('expresselect', ['dataService', '$compile', 'helper', '$timeout', 'dhfprinterService',
            function(dataService, $compile, helper, $timeout, dhfprinterService) {
                return {
                    restrict: 'EA',
                    require: 'ngModel',
                    scope: {
                        ngModel: '=',
                        tid: "@",
                        // printer: "=",
                    },
                    template: '<span><select ng-model="tmpNgModel"   ng-options="x.id as x.name for x in exprssdata"  ></select></span>',
                    controller: ['$templateCache', '$rootScope', '$scope',
                        function($templateCache, $rootScope, $scope) {
                            // $scope.exprssdata = {};

                            $scope.$watch('tmpNgModel', function(newvalue, oldValue) {
                                if (newvalue != oldValue && newvalue) {
                                    // console.log("$scope.newvalue", newvalue);
                                    $scope.ngModel = newvalue;
                                }
                            });


                            function initData() {
                                $scope.exprssdata = [{
                                        id: "LTS",
                                        name: "联昊通",
                                        en: "LTS",
                                    }, {
                                        id: "QFKD",
                                        name: "全峰快递",
                                        en: "QFKD",
                                    }, {
                                        id: "SCKJ",
                                        name: "四川快捷",
                                        en: "QFKD",
                                    }, {
                                        id: "UAPEX",
                                        name: "全一快递",
                                        en: "UAPEX",
                                    }, {
                                        id: "BJCS",
                                        name: "城市100",
                                        en: "UAPEX",
                                    }, {
                                        code: "EMS",
                                        name: "EMS",
                                        en: "EMS",
                                    }, {
                                        id: "YTO",
                                        name: "圆通速递",
                                        en: "YTO",
                                    }, {
                                        id: "ZTO",
                                        name: "中通速递",
                                        en: "ZTO",
                                    }, {
                                        id: "HZABC",
                                        name: "杭州爱彼西",
                                        en: "HZABC",
                                    }, {
                                        id: "ZJS",
                                        name: "宅急送",
                                        en: "ZJS",
                                    }, {
                                        id: "YD",
                                        name: "韵达快运",
                                        en: "YD",
                                    }, {
                                        id: "TTKDEX",
                                        name: "海航天天快递",
                                        en: "TTKDEX",
                                    }, {
                                        id: "BEST",
                                        name: "百世物流",
                                        en: "BEST",
                                    }, {
                                        id: "FEDEX",
                                        name: "联邦快递",
                                        en: "FEDEX",
                                    }, {
                                        id: "DBL",
                                        name: "德邦物流",
                                        en: "DBL",
                                    }, {
                                        id: "SHQ",
                                        name: "华强物流",
                                        en: "SHQ",
                                    }, {
                                        code: "WLB-STARS",
                                        name: "星辰急便",
                                        en: "WLB-STARS",
                                    }, {
                                        id: "HTKY",
                                        name: "汇通快运",
                                        en: "HTKY",
                                    }, {
                                        id: "CRE",
                                        name: "中铁快运",
                                        en: "CRE",
                                    }, {
                                        id: "WLB-ABC",
                                        name: "浙江ABC",
                                        en: "WLB-ABC",
                                    }, {
                                        id: "SF",
                                        name: "顺丰速运",
                                        en: "SF",
                                    }, {
                                        id: "CCES",
                                        name: "CCES",
                                        en: "STO",
                                    }, {
                                        id: "STO",
                                        name: "申通快递",
                                        en: "STO",
                                    }, {
                                        id: "ZY",
                                        name: "中远",
                                        en: "ZY",
                                    }, {
                                        id: "LB",
                                        name: "龙邦速递",
                                        en: "LB",
                                    }, {
                                        id: "FAST",
                                        name: "快捷速递",
                                        en: "FAST",
                                    }, {
                                        id: "DFH",
                                        name: "东方汇",
                                        en: "DFH",
                                    }, {
                                        code: "SY",
                                        name: "首业",
                                        en: "SY",
                                    }, {
                                        id: "YC",
                                        name: "远长",
                                        en: "YC",
                                    }, {
                                        id: "YCT",
                                        name: "黑猫宅急便",
                                        en: "YCT",
                                    }, {
                                        id: "XB",
                                        name: "新邦物流",
                                        en: "XB",
                                    }, {
                                        id: "NEDA",
                                        name: "港中能达",
                                        en: "UC",
                                    }, {
                                        id: "UC",
                                        name: "优速物流",
                                        en: "UC",
                                    }, {
                                        id: "QRT",
                                        name: "全日通快递",
                                        en: "QRT",
                                    }, {
                                        id: "ZTO,",
                                        name: "中通快递",
                                        en: "ZTO,",
                                    },
                                    {
                                        id: "DBL",
                                        name: "德邦快递",
                                        en: "DBL",
                                    },
                                    {
                                        id: "JYWL",
                                        name: "佳怡物流",
                                        en: "JYWL",
                                    }, {
                                        id: "SJWL",
                                        name: "商家物流",
                                        en: "SJWL",
                                    }
                                ];

                                // console.log("dddddddddddd", $scope.exprssdata);
                                $timeout(function() {
                                    $scope.selDfExpress().then(function() {
                                        if (!$scope.tmpNgModel) {
                                            $scope.tmpNgModel = $scope.exprssdata[0].id;
                                        }
                                        $scope.ngModel = $scope.tmpNgModel;
                                    });
                                });
                            }

                            $scope.selDfExpress = function() {
                                // var query = { "type_id": 1 };
                                if ($scope.tid) {
                                    return dataService.orderOne($scope.tid).then(function(one) {
                                        if (one) {
                                            if (one.shipping_corp) {
                                                $scope.tmpNgModel = one.shipping_corp;
                                            }
                                            if (!one.shipping_corp) {
                                                return dataService.printSellerGet({ query: { 'default_express': 1, "store_id": $rootScope.store_id } }).then(function(r) {
                                                    if (r.prints.length > 0) {
                                                        //设置默认快递公司
                                                        return $scope.tmpNgModel = r.prints[0].shipping_corp;
                                                    }
                                                });

                                            }
                                        }
                                    });
                                } else {
                                    return dataService.resolve();
                                }
                            }

                            initData();
                        }
                    ],

                    link: function(scope, element, attrs, ctrl) {

                    }
                }
            }
        ])
        .directive('xiaopaoPrint', ['dataService', '$compile', 'helper', '$timeout', 'dhfprinterService',
            function(dataService, $compile, helper, $timeout, dhfprinterService) {
                return {
                    restrict: 'EA',
                    scope: {
                        tid: "=",
                    },

                    template: '<span><button class="sui-btn btn-primary" ng-click="initData()" >打印</button></span>',
                    controller: ['$templateCache', '$rootScope', '$scope', '$state',
                        function($templateCache, $rootScope, $scope, $state) {
                            $scope.initData = function() {
                                dhfprinterService.prsocketOnmessage($scope.tid, 2);
                            }
                        }
                    ],

                    link: function(scope, element, attrs, ctrl) {

                    }
                }
            }
        ])
        .directive('templateName', ['dataService', '$compile', 'helper', '$timeout', 'dhfprinterService',
            function(dataService, $compile, helper, $timeout, dhfprinterService) {
                return {
                    restrict: 'EA',
                    scope: {
                        ngModel: "=",
                    },
                    template: '<span >{{name}}</span>',
                    controller: ['$templateCache', '$rootScope', '$scope', '$state',
                        function($templateCache, $rootScope, $scope, $state) {
                            $scope.name = "";
                            $scope.initData = function() {
                                dataService.printSellerGet({
                                    query: {
                                        print_id: $scope.ngModel
                                    }
                                }).then(function(result) {
                                    console.error("template_id", $scope.ngModel, result);
                                    if (result.prints) {
                                        $scope.name = result.prints[0].name;
                                        console.error("$scope.printersList", $scope.name);
                                    }
                                })
                            }
                            $scope.initData();
                        }
                    ],

                    link: function(scope, element, attrs, ctrl) {

                    }
                }
            }
        ])
        .directive('printOrder', ['dataService', '$compile', 'helper', '$timeout', 'dhfprinterService',
            function(dataService, $compile, helper, $timeout, dhfprinterService) {
                return {
                    restrict: 'EA',
                    scope: {
                        orderid: "=",
                        type: "@",
                    },
                    template: '<span ><button class="sui-btn btn-primary" ng-click="initData()" >打印</button></span>',
                    controller: ['$templateCache', '$rootScope', '$scope', '$state',
                        function($templateCache, $rootScope, $scope, $state) {
                            $scope.name = "";
                            $scope.initData =function(){
                                var data = {
                                    "store_id": $rootScope.store_id,
                                    "status": 1,
                                };
                                dataService.printerGet(data).then(function(result) {
                                    if (result.printers_list) {
                                        $scope.printreAppWork();
                                    } else {
                                        helper.message('打印机未连接！请先连接打印机！','error');
                                        return;
                                    }
                                })
                            }
                            //执行打印
                            $scope.printreAppWork =function(){
                                var data = {
                                    "order_id": $scope.orderid,
                                    "type": $scope.type,
                                    "timezone": window.localStorage.timezone,
                                };
                                dataService.printreAppWork(data).then(function(result) {
                                    console.error("template_id", $scope.ngModel, result);
                                    if (result.Msg) {
                                        helper.message('打印出错'+ result.Msg,"error");
                                        return;
                                    } else {
                                        helper.message('打印完成');
                                        return;
                                    }
                                })
                            }
                        }
                    ],

                    link: function(scope, element, attrs, ctrl) {

                    }
                }
            }
        ])
        //打印组件
        .run(["$templateCache", "dataService", function($templateCache, dataService) {
            var tplName = "views/directives.print.html";
            dataService.tpl(tplName).then(function(html) {
                $templateCache.put(tplName, html);
            });
        }])
        .directive('print', ['dataService', '$compile', 'helper', '$timeout', 'dhfprinterService',
            function(dataService, $compile, helper, $timeout, dhfprinterService) {
                return {
                    restrict: 'EA',
                    // require: 'ngModel',
                    scope: {
                        // ngModel: '=',
                        // express: "=",
                        tid: "@",
                    },

                    template: '<span><button class="sui-btn btn-primary" ng-click="initData()" >打印</button></span>',
                    controller: ['$templateCache', '$rootScope', '$scope', '$state',
                        function($templateCache, $rootScope, $scope, $state) {
                            $scope.exprssdata = {};

                            $scope.$watch('selecttpl', function(newvalue, oldValue) {
                                console.error("newvalue", newvalue, $scope.selectUserTpl);
                                _.map($scope.selectUserTpl, function(tp, k) {
                                    if (tp.print_id == newvalue) {
                                        $scope.defprinter = tp.default_printer;
                                        console.error("$scope.defprinter ", $scope.defprinter);
                                    }
                                });
                            });
                            //
                            // $scope.ciktmp =function(){
                            //     if($scope.selecttpl){
                            //         _.map($scope.selectUserTpl, function(tp, k) {
                            //             if ($scope.selecttpl == newvalue) {
                            //                 $scope.defprinter = tp.default_printer;
                            //             }
                            //         });
                            //     }
                            // }
                            $scope.initData = function() {
                                $scope.getTemplte().then(showPop);
                            }

                            function showPop() {
                                $.alert({
                                    backdrop: 'static',
                                    keyboard: true,
                                    title: '<span>{{"打印"|translate}}</span>',
                                    body: $templateCache.get("views/directives.print.html"),
                                    okBtn: 'ok',
                                    hasfoot: false,
                                    closeBtn: true,
                                    transition: true,
                                    width: '400px',
                                    show: function(e) {
                                        $compile($(e.currentTarget).contents())($scope);
                                        return true;
                                    },
                                    okHide: function(e) {

                                    },
                                });
                            }
                            $scope.upExpress = function() {
                                // "#/cainiao/list"
                                rmAlert();
                                $state.go('print.list');
                                // helper.myAlert("","#/print/list");
                            }

                            $scope.getTemplte = function() {
                                // var query = { "type_id": 1, };
                                return dataService.printSellerGet().then(function(result) {
                                    if (result.prints.length > 0) {
                                        var re = result.prints;
                                        $scope.Tpl = [];
                                        _.map(re, function(dd, kk) {
                                            if (!$scope.Tpl) {
                                                if (dd.shipping_corp) {
                                                    $scope.Tpl[dd.shipping_corp].push(dd);
                                                }
                                            }
                                            if ($scope.Tpl[dd.shipping_corp]) {
                                                $scope.Tpl[dd.shipping_corp].push(dd);
                                            } else {
                                                if (dd.shipping_corp) {
                                                    $scope.Tpl[dd.shipping_corp] = [];
                                                    $scope.Tpl[dd.shipping_corp].push(dd);
                                                }
                                            }
                                        });
                                        if ($scope.expressd) {
                                            $scope.selectUserTpl = $scope.Tpl[$scope.expressd];
                                            _.map($scope.selectUserTpl, function(tp, k) {
                                                if (tp.default_template) {
                                                    $scope.selecttpl = tp.print_id;
                                                }
                                                if (tp.default_printer) {
                                                    $scope.defprinter = tp.default_printer;
                                                }
                                            });
                                        }

                                        console.log(" $scope.selectUserTpl ", $scope.selectUserTpl);
                                    } else {

                                    }
                                });
                            }
                        }
                    ],

                    link: function(scope, element, attrs, ctrl) {
                        scope.$watch('expressd', function(newvalue, oldValue) {
                            console.log("newvalue", newvalue);
                            scope.getTemplte();
                        });
                    }
                }
            }
        ])
        // 
        .directive('printExpress', ['dataService', '$compile', 'helper', '$timeout', 'dhfprinterService', 'moment',
            function(dataService, $compile, helper, $timeout, dhfprinterService, moment) {
                return {
                    restrict: 'EA',
                    // require: 'ngModel',
                    scope: {
                        tid: '=',
                        templateid: "=",
                        defprinter: "=",
                    },
                    template: '<span><button class="sui-btn btn-primary" ng-click="initData()" >打印</button></span>',
                    controller: ['$templateCache', '$rootScope', '$scope',
                        function($templateCache, $rootScope, $scope) {

                            $scope.initData = function() {
                                if (!$scope.defprinter) {
                                    helper.myAlert('请先设置默认打印机，在进行打印！', "#/print/list");
                                    return;
                                }
                                dhfprinterService.wsPrintInitData($scope.defprinter, $scope.tid, $scope.templateid, 1).then(function(a) {
                                    console.log("返回结果：", a);
                                });

                                // console.error("$scope.defprinter", $scope.defprinter);
                                // $scope.printers = JSON.parse($scope.defprinter);
                                // // try {
                                // //     $scope.printers = JSON.parse($scope.defprinter);
                                // // } catch (e) {
                                // //     // $scope.item.description = "";
                                // // }
                                // console.log("tid", $scope.tid, $scope.templateid, $scope.defprinter, $scope.printers);
                                // $scope.getdata();
                            }

                            //获取模板数据
                            $scope.getdata = function() {
                                var data = {
                                    content: {
                                        "store_id": $rootScope.store_id,
                                        "tid": $scope.tid,
                                        "templateid": $scope.templateid,
                                        "timezone": window.localStorage.timezone,
                                    }
                                }
                                console.error("rootScope", $rootScope, window.localStorage.timezone);
                                return dataService.printPOs(data).then(function(result) {
                                    if (result) {

                                        if (result.type == 2) {
                                            $scope.printData = result;
                                            $scope.print();
                                        } else {
                                            $scope.printData = result.printdata;
                                            $scope.generateHtml().then($scope.print);
                                        }
                                        console.error("$scope.printData", $scope.printData);
                                    }
                                });
                            }

                            //解析模板参数
                            $scope.generateHtml = function() {
                                var g_express_info = JSON.parse($scope.printData.content);
                                var g_express = JSON.parse(g_express_info.value);
                                $scope.taghtmlstr = '';
                                for (var i = 0; i < g_express.length; i++) {
                                    var name = ' ';
                                    var possize = g_express[i]['left'] + ',' + g_express[i]['top'] + ',' + g_express[i]['width'] + ',' + g_express[i]['height'];
                                    if ($scope.printData[g_express[i]['id']]) {
                                        name = $scope.printData[g_express[i]['id']];
                                    }
                                    if (g_express[i]['id'] == 'zdy') {
                                        name = g_express[i]['name'];
                                    }

                                    $scope.taghtmlstr += MakeOnetagHtml(name, possize, 3, g_express[i]['font-family'], g_express[i]['font-size'], g_express[i]['font-weight'], g_express[i]['white-space'], g_express[i]['img'], g_express[i]['flg'], g_express[i]['id']);
                                }

                                return dataService.resolve($scope.html);
                            }

                            $scope.print = function() {
                                for (var i = $scope.printers.length - 1; i >= 0; i--) {
                                    var request_id = helper.guid();
                                    var html;
                                    var escpos = 0;
                                    if (!$scope.taghtmlstr) {
                                        escpos = 1;
                                        html = $scope.printData.printdata; // ="G0AdIQAcJhwuHSERHCYcLh0hABwmHC4dIQAcJhwuHSEAHCYcLh0hABwmHC4dIQAcJhwuHSERHCYcLh0hABwmHC4dIQAcJhwuHSEAHCYcLh0hABwmHC4dIQAcJhwuHSEAHCYcLh0hABwmHC4dIQAcJhwuHSEAHCYcLh0hABwmHC4dIQAcJhwuHSEAHCYcLh0hABwmHC4dIQAcJhwuHSEAHCYcLh0hABwmHC4dIQAcJhwuHSEi";
                                    } else {
                                        html = '<html><title>' + request_id + '</title><body><div >' + $scope.taghtmlstr + '</div></body></html>';
                                    }

                                    var testData = {
                                        sync: false, //是否同步打印，true：等待打印机打印完毕返回；false：任务提交给打印机返回，不能确定是否真实打印成功。默认false
                                        request_id: request_id, //每次请求的唯一id，如果是相同的打印内容，可以使用同一个request_id防止重复
                                        html: html,
                                        height: $scope.printData.height, //打印的页面高度，单位px
                                        width: $scope.printData.width, //打印的页面宽度，单位px
                                        printer: $scope.printers[i], //打印机名称，通过dhfprinterService.getPrinters获取
                                        parms: {
                                            escpos: escpos,
                                            // name: "大黄蜂", //其他参数，暂不用
                                            // title: "中国", //其他参数，暂不用
                                        },
                                    };
                                    console.log("testData", testData);
                                    testData.review = false; //不预览，直接打印
                                    dhfprinterService.print(testData).then(function(a) {
                                        console.log("返回结果：", a);
                                        var msg = a.msg ? a.msg : "打印成功";
                                        helper.myAlert(msg);
                                        return;
                                    });

                                }
                                // _.map($scope.defprinter,function(dyj,ke){

                                // });

                            }

                            //测试打印
                            $scope.printold = function() {
                                var testData = testdata();
                                console.log("testData", testData);
                                testData.review = false; //不预览，直接打印
                                dhfprinterService.print(testData).then(function(a) {
                                    console.log("返回结果：", a);
                                });
                            }
                        }
                    ],

                    link: function(scope, element, attrs, ctrl) {

                    }
                }
            }
        ])
        .run(["$templateCache", "dataService", function($templateCache, dataService) {
            var tplName = "views/directives.print.html";
            dataService.tpl(tplName).then(function(html) {
                $templateCache.put(tplName, html);
            });
        }])
        //设置默认打印机列表
        .directive('defPrinter', ['dataService', '$compile', 'helper', '$timeout', 'dhfprinterService',
            function(dataService, $compile, helper, $timeout, dhfprinterService) {
                return {
                    restrict: 'EA',
                    require: 'ngModel',
                    scope: {
                        ngModel: "=",
                        printid: "@",
                        check: "&", //回调方法
                        // html: "@"
                    },

                    template: '<span><a href="" ng-click="init()">[锁定打印机]</a></span>',
                    controller: ['$templateCache', '$rootScope', '$scope',
                        function($templateCache, $rootScope, $scope) {
                            // console.log("tmpData",$scope.printid,$scope.check);


                            $scope.init = function() {
                                $scope.ngModel = $scope.ngModel ? $scope.ngModel : {};
                                console.log("$scope.printers", $scope.printers);
                                $scope.getData().then($scope.tancShow);
                            }

                            $scope.getData = function() {
                                $scope.printers = {};
                                return dhfprinterService.getPrinters().then(function(a) {
                                    // console.log("返回结果：", a);
                                    var x = _.values(a.msg);
                                    $scope.printers = x;
                                    return $scope.printers;
                                    // console.error("$scope.ngModel",$scope.ngModel,$scope.printer);
                                });
                            }

                            $scope.tancShow = function() {
                                $.alert({
                                    backdrop: 'static',
                                    keyboard: true,
                                    title: '<span>{{"default printer"|translate}}</span>',
                                    body: '<span><span ng-repeat="item in printers"> <input type="checkbox" name="checkbox1" checklist-model="$parent.ngModel" checklist-value="item.name">{{item.name}}<br/></span></span>',
                                    okBtn: 'ok',
                                    closeBtn: true,
                                    transition: true,
                                    width: '400px',
                                    show: function(e) {
                                        $compile($(e.currentTarget).contents())($scope);
                                        return true;
                                    },
                                    okHide: function(e) {
                                        $timeout(function() {
                                            console.error("isprinter", $scope.ngModel);
                                            if ($scope.ngModel) {
                                                $scope.check({
                                                    updata: { "print_id": $scope.printid, "default_printer": $scope.ngModel },
                                                });
                                            }
                                        });
                                    },
                                });
                            }
                        }
                    ],

                    link: function(scope, element, attrs, ctrl) {

                    }
                }
            }
        ])

})();